//
//  RecordEditViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordEditViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "RecordEditMenuView.h"
#import "RecordEditSpectrumCollectionViewCell.h"
#import "FileManager.h"
#import "ChooseFileViewController.h"
#import "LocalRecordModel.h"

@interface RecordEditViewController ()<AVPlayerDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate, RecordEditMenuViewDataSource, RecordEditMenuViewDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    CGFloat spectrumGridWidth;
    BOOL isDragging;
    NSMutableArray *dataMutArr;
    LocalRecordModel *selectModel;
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic, strong) CustomLineView *line;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation RecordEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"剪辑";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"保存"]) addTarget:self action:@selector(savePress) forControlEvents:UIControlEventTouchUpInside];

    dataMutArr = [NSMutableArray array];
    for (LocalRecordModel *model in self.contentArr) {
        [dataMutArr addObject:[model copy]];
    }
    LocalRecordModel *firstModel = [dataMutArr firstObject];
    firstModel.isSelected = YES;
    selectModel = firstModel;
    [self seeAudio:selectModel];
    [self initView];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    [AVPlayerManager manager].delegate = nil;
}

- (void)savePress {
    if (dataMutArr.count > 1) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionBtn1 = [UIAlertAction actionWithTitle:@"分开保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self separateSaveHandle];
        }];
        [alertController addAction:actionBtn1];
        UIAlertAction *actionBtn2 = [UIAlertAction actionWithTitle:@"合并音频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self mergeSaveHandle];
        }];
        [alertController addAction:actionBtn2];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        [self separateSaveHandle];
    }
}

//分开保存处理
- (void)separateSaveHandle {
    for (LocalRecordModel *model in dataMutArr) {
        if (model.needSaveUrl) {
            NSString *destPath = [[FileManager sharedManager] getLocalFilePath:model.fileName];
            NSURL *destURL = [NSURL fileURLWithPath:destPath];
            if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
                [[NSFileManager defaultManager] removeItemAtPath:destPath error:nil];
            }
            NSError *error;
            BOOL success = [[NSFileManager defaultManager] copyItemAtURL:model.needSaveUrl toURL:destURL error:&error];
            if (success) {
                [UserManger createFileModel:model];
            }
        }
    }
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.SaveHandle) {
            self.SaveHandle();
        }
    }];
}

//合并保存
- (void)mergeSaveHandle {
    [self loadingHUDAlert];
    LocalRecordModel *localModel = [[LocalRecordModel alloc] initMerge];
    NSMutableArray *pathMutArr = [NSMutableArray array];
    for (LocalRecordModel *item in dataMutArr) {
        if (item.needSaveUrl) {
            [pathMutArr addObject:[item.needSaveUrl absoluteString]];
        } else {
            [pathMutArr addObject:[[FileManager sharedManager] getLocalFilePath:item.fileName]];
        }
    }
    [AVPlayerManager mergeAudios:pathMutArr destnation:[[FileManager sharedManager] getLocalFilePath:localModel.fileName] completed:^(NSString *successPath) {
        [UserManger createFileModel:localModel];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [self dismissViewControllerAnimated:YES completion:^{
                if (self.SaveHandle) {
                    self.SaveHandle();
                }
            }];
        });
    }];
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [[AVPlayerManager manager] pause];
    } else {
        [[AVPlayerManager manager] play];
    }
}

- (void)seeAudio:(LocalRecordModel *)model {
    NSURL *url = nil;
    if (model.needSaveUrl) {
        url = model.needSaveUrl;
    } else {
        url = [NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:selectModel.fileName]];
    }
    [[AVPlayerManager manager] pause];
    [self trackPlayDidEnd];
    [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [[AVPlayerManager manager] setAVPlayerURL:url];
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    duration = CMTimeGetSeconds(asset.duration);
    __weak __typeof(self) weakSelf = self;
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
        imgv.image = spectrumImage;
        [weakSelf.waveScrollView addSubview:imgv];
        UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
        scaleImgv.image = scaleImage;
        [weakSelf.waveScrollView addSubview:scaleImgv];
    }];
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [[AVPlayerManager manager] pause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];

//    [[AVPlayerManager manager] play];
//    self.actionBtn.selected = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView ==  scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*duration;
        if (currentTime > duration) {
            currentTime = duration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
//        int allMin  = (int)duration / 60;
//        int allSecond  = (int)duration % 60;
//        int allMillisecond  = (duration - allSecond)*100;
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
    //    NSString *aullTime = [NSString stringWithFormat:@"%.2d:%.2d.%02d",allMin,allSecond,allMillisecond];
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

#pragma mark ---AVPlayerDelegate---
- (void)timeRunAndTime:(double)runTime andValue:(NSString *)value andScale:(CGFloat)scale {
    currentTime = runTime;
    self.timeLabel.text = value;
    if ([AVPlayerManager manager].isPlaying) {
        CGFloat pointX = (self.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
        if (pointX < self.waveScrollView.contentOffset.x) {
            pointX = self.waveScrollView.contentOffset.x;
        }
        [UIView animateWithDuration:0.1 animations:^{
            [self.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
        }];
    }
}

- (void)trackPlayDidEnd {
    self.actionBtn.selected = NO;
    [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 50 - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];
    
    RecordEditMenuView *menuView = [[RecordEditMenuView alloc] initCustomView:CGRectMake(0, SCREEN_HEIGHT_DEVICE - 50 - IS_iPhoneX_Bottom, SCREEN_WIDTH_DEVICE, 40)];
    menuView.dataSource = self;
    menuView.delegate = self;
    [self.view addSubview:menuView];
    
    [self configCollectionView];

}

#pragma mark RecordEditMenuViewDataSource & RecordEditMenuViewDelegate
- (LocalRecordModel *)dataSourceLocalRecord {
    return selectModel;
}

- (NSArray *)dataSourceArray {
    return dataMutArr;
}

- (void)recordEditMenuViewCutReloadUrl:(NSURL *)url name:(NSString *)fileName{
    LocalRecordModel *localModel = [[LocalRecordModel alloc] initRecord:[url pathExtension]];
    localModel.needSaveUrl = url;
    localModel.nickName = [NSString stringWithFormat:@"%@-%@", selectModel.nickName, fileName];
    localModel.isSelected = YES;
    NSInteger index = [dataMutArr indexOfObject:selectModel];
    [dataMutArr replaceObjectAtIndex:index withObject:localModel];
    selectModel = localModel;
    [self seeAudio:localModel];
    [self.collectionView reloadData];
}

- (void)recordEditMenuViewSplitReloadModels:(NSArray *)arr {
    NSInteger index = [dataMutArr indexOfObject:selectModel];
    [dataMutArr removeObject:selectModel];
    for (NSInteger i = index; i < arr.count+index; i++) {
        LocalRecordModel *model = [arr objectAtIndex:i];
        [dataMutArr insertObject:model atIndex:i];
        if (i == index) {
            model.isSelected = YES;
        } else {
            model.isSelected = NO;
        }
    }
    selectModel = [arr firstObject];
    [self seeAudio:selectModel];
    [self refreshCollectionViewFrame];
    [self.collectionView reloadData];
}

- (void)recordEditMenuViewReloadModels:(NSArray *)arr {
    [dataMutArr removeAllObjects];
    [dataMutArr addObjectsFromArray:arr];
    selectModel = [arr firstObject];
    selectModel.isSelected = YES;
    [self seeAudio:selectModel];
    [self refreshCollectionViewFrame];
    [self.collectionView reloadData];
}

- (void)recordEditMenuViewDelete:(LocalRecordModel *)dModel {
    [dataMutArr removeObject:dModel];
    [UserManger removeFileModel:dModel];
    if (dataMutArr.count == 0) {
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[ChooseFileViewController class]]) {
                [self.navigationController popToViewController:obj animated:YES];
                *stop = YES;
            }
        }];
    } else {
        selectModel = [dataMutArr firstObject];
        selectModel.isSelected = YES;
        [self seeAudio:selectModel];
        [self refreshCollectionViewFrame];
        [self.collectionView reloadData];
    }
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return dataMutArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * CellIdentifier = @"RecordEditSpectrumCell";
    RecordEditSpectrumCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if (dataMutArr.count == 1) {
        cell.onlyOneData = YES;
    } else {
        cell.onlyOneData = NO;
    }
    cell.indexRow = indexPath.row;
    cell.model = [dataMutArr objectAtIndex:indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LocalRecordModel *model = [dataMutArr objectAtIndex:indexPath.row];
    if (model != selectModel) {
        NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:[dataMutArr indexOfObject:selectModel] inSection:0];
        selectModel.isSelected = NO;
        model.isSelected = YES;
        selectModel = model;
        [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:indexPath, oldIndexPath, nil]];
        [self seeAudio:selectModel];
    }
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    LocalRecordModel *model = [dataMutArr objectAtIndex:sourceIndexPath.row];
    [dataMutArr removeObject:model];
    [dataMutArr insertObject:model atIndex:destinationIndexPath.row];
    [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:sourceIndexPath, destinationIndexPath, nil]];
}

- (void)configCollectionView {
    [self refreshCollectionViewFrame];
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[RecordEditSpectrumCollectionViewCell class] forCellWithReuseIdentifier:@"RecordEditSpectrumCell"];
    UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    [self.collectionView addGestureRecognizer:longPresssGes];
}

- (void)refreshCollectionViewFrame {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    if (dataMutArr.count == 1) {
        layout.itemSize = CGSizeMake(SCREEN_WIDTH_DEVICE - 32, 85);
    } else {
        layout.itemSize = CGSizeMake(122, 85);
    }
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 16, 0, 16);
    self.collectionView.collectionViewLayout = layout;
}

- (void)longPressMethod:(UILongPressGestureRecognizer *)longPressGes {
    // 判断手势状态
    switch (longPressGes.state) {
        case UIGestureRecognizerStateBegan: {
            // 判断手势落点位置是否在路径上(长按cell时,显示对应cell的位置,如path = 1 - 0,即表示长按的是第1组第0个cell). 点击除了cell的其他地方皆显示为null
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPressGes locationInView:self.collectionView]];
            // 如果点击的位置不是cell,break
            if (nil == indexPath) {
                break;
            }
            NSLog(@"%@",indexPath);
            // 在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:
            // 移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longPressGes locationInView:self.collectionView]];
            break;
        case UIGestureRecognizerStateEnded:
            // 移动结束后关闭cell移动
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}
@end
